<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page import="java.util.List" %>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>主题查询页面</title>
    <!-- 引入Layui CSS -->
    <link rel="stylesheet" href="https://cdn.staticfile.org/layui/2.8.17/css/layui.min.css">
    <link rel="stylesheet" href="<c:url value="/css/layui.min.css"/>">
    <!-- 引入Font Awesome -->
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">

    <!-- 引入Layui JS -->
    <script src="https://cdn.staticfile.org/layui/2.8.17/layui.min.js"></script>
    <style>
        body {
            background-color: #f8f9fa;
            margin: 0;
            padding: 0;
            font-family: 'Helvetica Neue', Arial, sans-serif;
            padding-bottom: 80px; /* 为固定的分页控件留出空间 */
        }

        .card-status {
            display: inline-block;
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
            margin-bottom: 12px;
            white-space: nowrap;
        }

        .status-running {
            background-color: rgba(30, 159, 255, 0.1);
            color: #1E9FFF;
        }

        .status-not-started {
            background-color: rgba(126, 136, 149, 0.1);
            color: #7E8895;
        }

        .status-finished {
            background-color: rgba(220, 53, 69, 0.1);
            color: #dc3545;
        }

        .status-deleted {
            background-color: rgba(220, 53, 69, 0.1);
            color: #676767;
        }

        .meta-item i {
            color: #999;
            margin-right: 8px;
            width: 18px;
            text-align: center;
        }

        /*.header {*/
        /*    background-color: #ffffff;*/
        /*    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08);*/
        /*    padding: 15px 30px;*/
        /*    display: flex;*/
        /*    flex-wrap: wrap;*/
        /*    justify-content: center;*/
        /*    gap: 10px;*/
        /*}*/

        .search-group {
            display: flex;
            align-items: center;
            margin: 5px 0;
        }

        .search-label {
            min-width: 60px;
            text-align: right;
            margin-right: 5px;
            color: #555;
        }

        .search-input {
            padding: 8px;
            border: 1px solid #ccc;
            border-radius: 5px;
            width: 150px;
            transition: border-color 0.3s;
        }

        .search-input:focus {
            border-color: #1E9FFF;
            outline: none;
        }

        .date-range {
            display: flex;
            align-items: center;
        }

        .date-separator {
            margin: 0 5px;
            color: #999;
        }

        .search-button {
            padding: 8px 15px;
            border: none;
            border-radius: 5px;
            background-color: #1E9FFF;
            color: #fff;
            cursor: pointer;
            transition: background-color 0.3s ease;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .search-button:hover {
            background-color: #007BFF;
            transform: translateY(-1px);
        }

        .search-button i {
            margin-right: 5px;
        }

        .theme-cards {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
            gap: 24px;
            padding: 30px;
        }

        .theme-card {
            background-color: #fff;
            border-radius: 14px;
            overflow: hidden;
            box-shadow: 0 4px 16px rgba(0, 0, 0, 0.05);
            transition: transform 0.3s ease, box-shadow 0.3s ease;
            display: flex;
            flex-direction: column;
            height: 100%;
        }

        .theme-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
        }

        .card-image {
            width: 100%;
            height: 180px;
            object-fit: cover;
            transition: transform 0.5s ease;
        }

        .theme-card:hover .card-image {
            transform: scale(1.03);
        }

        .card-content {
            padding: 20px;
            flex-grow: 1;
            display: flex;
            flex-direction: column;
        }

        .card-status {
            display: inline-block;
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
            margin-bottom: 12px;
            white-space: nowrap;
        }

        .status-running {
            background-color: rgba(30, 159, 255, 0.1);
            color: #1E9FFF;
        }

        .status-not-started {
            background-color: rgba(126, 136, 149, 0.1);
            color: #7E8895;
        }

        .status-finished {
            background-color: rgba(220, 53, 69, 0.1);
            color: #dc3545;
        }

        .status-deleted {
            background-color: rgba(220, 53, 69, 0.1);
            color: #676767;
        }

        .card-title {
            font-size: 18px;
            font-weight: 600;
            margin-bottom: 12px;
            color: #333;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
        }

        .card-meta {
            display: flex;
            flex-direction: column;
            gap: 8px;
            margin-bottom: 20px;
            color: #666;
            font-size: 14px;
        }

        .meta-item {
            display: flex;
            align-items: center;
        }

        .meta-item i {
            color: #999;
            margin-right: 8px;
            width: 18px;
            text-align: center;
        }

        .card-actions {
            display: flex;
            gap: 10px;
            margin-top: auto;
        }

        .card-actions button {
            background-color: transparent;
            border: 1px solid #e0e2e5;
            cursor: pointer;
            padding: 8px 12px;
            border-radius: 6px;
            transition: all 0.2s ease;
            display: flex;
            align-items: center;
            font-size: 13px;
            flex-grow: 1;
            justify-content: center;
        }

        .card-actions .edit-btn {
            color: #1E9FFF;
            border-color: #d0e8ff;
        }

        .card-actions .edit-btn:hover {
            background-color: #e6f2ff;
            border-color: #a8d5ff;
        }

        .card-actions .delete-btn {
            color: #dc3545;
            border-color: #f8d7da;
        }

        .card-actions .delete-btn:hover {
            background-color: #fce9eb;
            border-color: #f5c2c7;
        }

        /* 固定分页样式 */
        .pagination-container {
            position: fixed;
            bottom: 0;
            left: 0;
            width: 100%;
            background-color: #fff;
            padding: 15px 0;
            box-shadow: 0 -5px 15px rgba(0, 0, 0, 0.05);
            z-index: 999;
            transition: all 0.3s ease;
        }

        .pagination-container:hover {
            box-shadow: 0 -5px 15px rgba(0, 0, 0, 0.1);
        }

        .pagination {
            display: inline-flex;
            list-style: none;
            padding: 0;
            margin: 0;
        }

        .pagination li {
            margin: 0 5px;
        }

        .pagination li a {
            display: inline-block;
            padding: 8px 14px;
            border-radius: 5px;
            text-decoration: none;
            color: #333;
            background-color: #f0f0f0;
            transition: all 0.3s ease;
        }

        .pagination li a:hover,
        .pagination li.active a {
            background-color: #1E9FFF;
            color: #fff;
        }

        @media (max-width: 480px) {
            .theme-cards {
                grid-template-columns: 1fr;
            }


            .module-actions button {
                justify-content: center;
            }

            .card-actions {
                flex-direction: column;
                gap: 8px;
            }
        }

        /* 响应式调整 */
        @media (max-width: 768px) {
            .voteResult-container {
                padding: 30px 10px;
                grid-template-columns: 1fr;
            }

            .header {
                padding: 15px 10px;
                flex-direction: column;
                align-items: stretch;
            }

            .search-group {
                width: 100%;
            }

            .search-input {
                width: 100%;
            }

            .date-range {
                width: 100%;
            }

            .search-button {
                width: 100%;
                margin-top: 10px;
            }

            .pagination-container {
                padding: 10px 0;
            }

            .pagination li a {
                padding: 6px 10px;
                font-size: 14px;
            }
        }

        .header {
            background-color: #ffffff;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08);
            padding: 15px 30px;
            display: flex;
            align-items: center;
        }

        .header a {
            color: #333;
            margin-left: 25px;
            text-decoration: none;
            transition: color 0.3s ease;
            font-size: 15px;
        }

        .header a:hover {
            color: #1E9FFF;
        }

        .header > a:first-child {
            margin-left: 0;
        }

        .ml-auto {
            margin-left: auto;
        }
    </style>
</head>
<body>
<nav class="header">

    <c:if test="${person.level == 1}">
        <a href="${pageContext.request.contextPath}/person/index" class="flex items-center">
            <i class="fa fa-home text-primary text-xl mr-2"></i>
            <span class="font-bold text-lg">用户首页</span>
        </a>
        <a href="${pageContext.request.contextPath}/admin/index" class="flex items-center">
            <i class="fa fa-home text-primary text-xl mr-2"></i>
            <span class="font-bold text-lg">管理员首页</span>
        </a>
    </c:if>
    <c:if test="${person.level == 0}">
        <a href="${pageContext.request.contextPath}/person/index" class="flex items-center">
            <i class="fa fa-home text-primary text-xl mr-2"></i>
            <span class="font-bold text-lg">用户首页</span>
        </a>
    </c:if>

    <div class="ml-auto flex items-center">
        <c:if test="${person == null}">
            <a href="${pageContext.request.contextPath}/views/login.jsp"><i class="fa fa-user-circle mr-2"></i>请先登录</a>
        </c:if>
        <c:if test="${person != null}">
            <a href="${pageContext.request.contextPath}/admin/person/editPerson?pid=${person.pid}"><i
                    class="fa fa-user-circle mr-2"></i>${person.username}</a>
        </c:if>

        <a href="javascript:void(0);" onclick="logout()">退出登录</a>
    </div>
</nav>

<div class="header">
    <div class="search-group">
        <span class="search-label">ID搜索：</span>
        <input type="text" class="search-input" id="idSearch" placeholder="输入主题ID">
    </div>
    <div class="search-group">
        <span class="search-label">主题名：</span>
        <input type="text" class="search-input" id="titleSearch" placeholder="输入主题名称">
    </div>
    <div class="search-group">
        <span class="search-label">日期范围：</span>
        <div class="date-range">
            <input type="text" class="search-input" id="startDate" placeholder="开始日期">
            <span class="date-separator">至</span>
            <input type="text" class="search-input" id="endDate" placeholder="结束日期">
        </div>
    </div>
    <div class="search-group">
        <span class="search-label">状态：</span>
        <select class="search-input" id="statusSearch" lay-verify="required">
            <option value="-1">请选择状态</option>
            <option value="0">待开始</option>
            <option value="1">正在投票</option>
            <option value="2">已过期</option>
            <option value="3">已删除</option>
        </select>
    </div>
    <button class="search-button" id="searchBtn">
        <i class="fa fa-search"></i> 查询
    </button>
</div>


<div class="theme-cards" id="tc">
    <!-- 主题卡片：已结束 -->

</div>

<!-- 固定分页控件 -->
<%--    <div class="pagination-container">--%>
<%--        <div class="layui-container" style="text-align: center;">--%>
<%--            <ul class="pagination">--%>
<%--                <li><a href="javascript:void(0);" id="prevPage"><i class="fa fa-angle-left"></i> 上一页</a></li>--%>
<%--                <li class="active"><a href="javascript:void(0);">1</a></li>--%>
<%--                <li><a href="javascript:void(0);">2</a></li>--%>
<%--                <li><a href="javascript:void(0);">3</a></li>--%>
<%--                <li><a href="javascript:void(0);" id="nextPage">下一页 <i class="fa fa-angle-right"></i></a></li>--%>
<%--            </ul>--%>
<%--        </div>--%>
</div>


<script>
    layui.use(['form', 'layer', 'laydate', 'element'], function () {
        var form = layui.form;
        var layer = layui.layer;
        var laydate = layui.laydate;
        var $ = layui.jquery;


        // 初始化开始日期选择器
        var startDateIns = laydate.render({
            elem: '#startDate',
            type: 'date',
            format: 'yyyy-MM-dd',
            trigger: 'click',
            done: function (value, date) {
                // 设置结束日期的最小值为开始日期
                endDateIns.config.min = date;
            }
        });

        // 初始化结束日期选择器
        var endDateIns = laydate.render({
            elem: '#endDate',
            type: 'date',
            format: 'yyyy-MM-dd',
            trigger: 'click',
            done: function (value, date) {
                // 设置开始日期的最大值为结束日期
                startDateIns.config.max = date;
            }
        });

        // 渲染表单元素
        form.render();

        // 搜索按钮点击事件
        $('#searchBtn').on('click', function () {
            const tid = $('#idSearch').val();
            const title = $('#titleSearch').val();
            const beginDate = $('#startDate').val();
            const endDate = $('#endDate').val();
            const status = $('#statusSearch').val();

            // 验证日期范围
            if (beginDate && endDate && beginDate > endDate) {
                layer.msg('开始日期不能大于结束日期', {icon: 5});
                return;
            }

            // 显示加载动画
            const loading = layer.load(1, {
                shade: [0.1, '#fff']
            });

            // 发送AJAX请求
            $.ajax({
                url: '/VoingSystem/admin/topic/findTopic',
                type: 'POST',
                data: {tid, title, beginDate, endDate, status},
                dataType: 'json', // 明确指定返回JSON类型，让jQuery自动解析
                success: function (data) {
                    console.log('返回数据类型:', typeof data, '数据内容:', data);
                    // 关闭加载动画
                    layer.close(loading);

                    let tc = $('#tc');
                    // 检查返回数据是否有效
                    if (data && data.length > 0) {
                        // 生成投票卡片
                        let html = '';
                        data.forEach(function (topic, index) {
                            // 确定状态样式和文本
                            let statusClass = '';
                            let statusText = '';

                            // 支持数字和字符串类型的状态值
                            if (topic.status === 1 || topic.status === '1' || topic.status === 'voting') {
                                statusClass = 'status-running';
                                statusText = '正在投票';
                            } else if (topic.status === 0 || topic.status === '0' || topic.status === 'pending') {
                                statusClass = 'status-not-started';
                                statusText = '待开始';
                            } else if (topic.status === 2 || topic.status === '2' || topic.status === 'expired') {
                                statusClass = 'status-finished';
                                statusText = '已过期';
                            } else {
                                statusClass = 'status-deleted';
                                statusText = '已删除';
                            }

                            var beginDate = formatTimestamp(topic.beginDate)
                            var endDate = formatTimestamp(topic.endDate)
                            console.log(topic.beginDate)
                            console.log(topic.endDate)
                            // 构建完整的卡片HTML结构
                            html += `    <div class="theme-card" >
                                        <img src="/VoingSystem` + topic.url + `" alt="` + topic.title + `"
                                             class="card-image" onclick="voteResult(` + topic.tid + `)">
                                        <div class="card-content">


                                            <span class="card-status  ` + statusClass + ` ">` + statusText + `</span>


                                            <h3 class="card-title">` + topic.title + `</h3>
                                            <div class="card-meta">
                                                <div class="meta-item"><i class="fa fa-user"></i> 创建者：` + topic.author + `</div>
                                                <div class="meta-item"><i class="fa fa-calendar"></i> ` + beginDate + `
                                                    至 ` + endDate + `
                                                </div>
                                            </div>
                                            <div class="card-actions">
                                                <button onclick="editTopic(` + topic.tid + `)" class="edit-btn"><i
                                                        class="fa fa-pencil mr-2"></i> 编辑
                                                </button>
                                                <button onclick="delTop(` + topic.tid + `)" class="delete-btn"><i
                                                        class="fa fa-trash mr-2"></i> 删除
                                                </button>
                                            </div>
                                        </div>
                                    </div>`
                        });

                        // 更新容器内容
                        tc.html(html);

                        // 重新绑定卡片点击事件
                        bindVoteBoxEvents();

                        // 显示成功消息
                        layer.msg(`共找到 ` + data.length + ` 个主题`, {icon: 1});
                    } else {
                        // 没有数据
                        tc.html(`
                        <div class="col-span-full text-center py-16">
                            <i class="fa fa-search fa-5x text-neutral-300 mb-4"></i>
                            <p class="text-neutral-500 text-lg">没有找到匹配的主题</p>
                        </div>
                    `);
                        layer.msg('未找到匹配数据', {icon: 2});
                    }
                },
                error: function (error) {
                    // 关闭加载动画
                    layer.close(loading);
                    console.error('AJAX请求错误:', error);
                    layer.msg('查询失败，请重试', {icon: 2});
                }
            });
        });


        // 转换时间
        function formatTimestamp(timestamp) {
            const date = new Date(timestamp);
            console.log(date)
            const year = date.getFullYear();
            console.log('year', year)
            // 月份从 0 开始，+1 后补 0
            const month = String(date.getMonth() + 1).padStart(2, '0');
            console.log('month', month)
            const day = String(date.getDate()).padStart(2, '0');
            console.log('day', day)
            return (year + '-' + month + '-' + day);
        }


        // 封装投票卡片点击事件绑定函数
        function bindVoteBoxEvents() {
            $('.theme-cards').on('click', function () {
                const status = $(this).data('status');
                const title = $(this).find('.voteResult-title').text();
                const id = $(this).data('id');

                if (status === '1' || status === 1 || status === 'voting') {
                    layer.msg(`即将跳转到 ${title} 的投票页面`, {icon: 1});
                    // 实际项目中替换为真实跳转
                    // window.location.href = `voteDetail.jsp?id=${id}`;
                } else if (status === '0' || status === 0 || status === 'pending') {
                    layer.msg('投票尚未开始', {icon: 5});
                } else if (status === '2' || status === 2 || status === 'expired') {
                    layer.msg(`即将查看 ${title} 的投票结果`, {icon: 1});
                    // 实际项目中替换为真实跳转
                    // window.location.href = `voteResult.jsp?id=${id}`;
                }
            });
        }

        // 为所有投票卡片添加点击事件
        $('.voteResult-box').on('click', function () {
            const status = $(this).data('status');
            const title = $(this).find('.voteResult-title').text();
            const id = $(this).data('id');

            if (status === 'voting') {
                layer.msg(`即将跳转到 ${title} 的投票页面`, {icon: 1});
                // 实际项目中替换为真实跳转
                // window.location.href = `voteDetail.jsp?id=${id}`;
            } else if (status === 'pending') {
                layer.msg('投票尚未开始', {icon: 5});
            } else if (status === 'expired') {
                layer.msg(`即将查看 ${title} 的投票结果`, {icon: 1});
                // 实际项目中替换为真实跳转
                // window.location.href = `voteResult.jsp?id=${id}`;
            }
        });

        // 分页按钮事件
        $('#prevPage, #nextPage').on('click', function () {
            layer.msg('切换到下一页', {icon: 1});
            // 实际项目中替换为AJAX加载下一页数据
        });

        // 滚动时调整分页控件样式
        $(window).on('scroll', function () {
            const scrollTop = $(this).scrollTop();
            const paginationContainer = $('.pagination-container');

            if (scrollTop > 50) {
                paginationContainer.addClass('shadow-lg');
            } else {
                paginationContainer.removeClass('shadow-lg');
            }
        });
    });


    // 删除主题
    function delTop(tid) {
        layer.confirm('确定要删除这个主题吗？', {
            icon: 3,
            title: '提示'
        }, function (index) {
            // 这里添加退出登录的实际逻辑
            layer.msg('已成功删除', {icon: 1});
            setTimeout(function () {
                window.location.href = '/VoingSystem/admin/topic/delTopic?tid=' + tid;
                // window.location.href = '/VoingSystem/logout';
            }, 1500);
            layer.close(index);
        })
    }

    function editTopic(tid) {
        window.location.href = '/VoingSystem/admin/topic/editTopic?tid=' + tid;
    }

    function logout() {
        layer.confirm('确定要退出登录吗？', {
            icon: 3,
            title: '提示'
        }, function (index) {
            // 这里添加退出登录的实际逻辑
            layer.msg('已成功退出登录', {icon: 1});
            setTimeout(function () {
                window.location.href = '/VoingSystem/logout';
            }, 1500);
            layer.close(index);
        })
    }

    function voteResult(tid) {
        window.location.href = '${pageContext.request.contextPath}/vote/show?tid=' + tid
    }
</script>
</body>
</html>